<script setup lang="ts">
import { ref, onBeforeUnmount, reactive, onMounted,  type Ref } from 'vue';
import { useRouter } from 'vue-router';

import { $t } from '@vben/locales';
import { VbenButton } from '@vben-core/shadcn-ui';

import { useQRCode } from '@vueuse/integrations/useQRCode';

import Title from './auth-title.vue';
import { DEFAULT_HOME_PATH, LOGIN_PATH } from '@vben/constants';

const accessStore = useAccessStore();
const userStore = useUserStore();
const router = useRouter();


interface Props {
  /**
   * @zh_CN 是否处于加载处理状态
   */
  loading?: boolean;
  /**
   * @zh_CN 登陆路径
   */
  loginPath?: string;

  /**
   * @zh_CN 登陆二维码路径
   */
   qrcodeSrc?: string;
   /**
   * @zh_CN 登录客户端id
   */
   client_id: string;
}

defineOptions({
  name: 'AuthenticationQrCodeLogin',
});

const props = withDefaults(defineProps<Props>(), {
  loading: false,
  loginPath: '/auth/login',
  qrcodeSrc: '',  ///https://imeal.weiyoho.com/assets/qrcode/login.png
  client_id: ""
});

const text = ref('https://www.uctoo.com');

const qrcode = useQRCode(text, {
  errorCorrectionLevel: 'H',
  margin: 4,
});

function goToLogin() {
  router.push(props.loginPath);
}



// WebSocket消息类型
interface WebSocketMessage {
  type: 'message' | 'system'
  content: string
  timestamp: number
  clientId?: string
}

// 响应式状态
const isConnected: Ref<boolean> = ref(false)
const messageInput: Ref<string> = ref('')
const messages = reactive<string[]>([])
let socket: WebSocket | null = null

// 初始化带ClientID的WebSocket
const initWebSocket = (): void => {
  const clientId = props.client_id
  console.log("initWebSocket");
  console.log(clientId);
  const wsUrl = `wss://imeal.weiyoho.com/ws/auth/qrcodelogin/${encodeURIComponent(clientId)}?client_id=${encodeURIComponent(clientId)}`
  
  socket = new WebSocket(wsUrl)

  socket.onopen = (event: Event) => {
    isConnected.value = true
    console.log('连接建立', event)
    sendSystemMessage('Connection established')
  }

  socket.onmessage = (event: MessageEvent<string>) => {
    try {
      const data = JSON.parse(event.data) as WebSocketMessage
      messages.push(`[${data.type}] ${data.content}`)
      const resData = JSON.parse(data.content);
      // 如果成功获取到 accessToken
      if (resData.access_token) {
        let userInfo: any = null;
        const access_token =  resData.access_token;
        const refresh_token =  resData.refresh_token;
        const user = resData.user
        // 将 accessToken 存储到 accessStore 中
        accessStore.setAccessToken(access_token);
        accessStore.setRefreshToken(refresh_token);

        userInfo = user;

        userStore.setUserInfo(userInfo);
        // accessStore.setAccessCodes(accessCodes);

        if (accessStore.loginExpired) {
          accessStore.setLoginExpired(false);
        } else {
          
        }

        localStorage.setItem('accessToken', access_token);

        router.push(userInfo.homePath || DEFAULT_HOME_PATH);

        if (userInfo?.name) {
          notification.success({
            description: `${$t('authentication.loginSuccessDesc')}:${userInfo?.name}`,
            duration: 3,
            message: $t('authentication.loginSuccess'),
          });
        }
      }


    } catch (error) {
      console.error('消息解析失败', error)
    }
  }

  socket.onerror = (event: Event) => {
    console.error('WebSocket错误:', event)
  }

  socket.onclose = (event: CloseEvent) => {
    isConnected.value = false
    console.log('连接关闭:', event)
    sendSystemMessage('Connection closed')
  }
}

// 发送系统消息（带ClientID）
const sendSystemMessage = (content: string): void => {
  if (!socket || socket.readyState !== WebSocket.OPEN) return
  
  const message: WebSocketMessage = {
    type: 'system',
    content,
    timestamp: Date.now(),
    clientId: props.client_id
  }
  socket.send(JSON.stringify(message))
}

// 发送用户消息
const sendMessage = (): void => {
  const content = messageInput.value.trim()
  if (!content || !socket || socket.readyState !== WebSocket.OPEN) return

  const message: WebSocketMessage = {
    type: 'message',
    content,
    timestamp: Date.now(),
    clientId: props.client_id
  }
  
  socket.send(JSON.stringify(message))
  messages.push(`[发送] ${content}`)
  messageInput.value = ''
}

// 连接管理
const toggleConnection = (): void => {
  isConnected.value ? socket?.close() : initWebSocket()
}
//

onMounted(async () => {
  //建立websocket连接，接收扫码登录结果
  console.log('conMounted');
  console.log(props.client_id);
  await initWebSocket();


});
// 组件卸载时清理
onBeforeUnmount(() => {
  if (socket?.readyState === WebSocket.OPEN) {
    socket.close()
  }
})
</script>

<template>
  <div>
    <Title>
      {{ $t('authentication.welcomeBack') }} 📱
      <template #desc>
        <span class="text-muted-foreground">
          {{ $t('authentication.qrcodeSubtitle') }}
        </span>
      </template>
    </Title>

    <div class="flex-col-center mt-6">
      <img :src="qrcodeSrc" alt="qrcode" class="w-1/2" />
      <p class="text-muted-foreground mt-4 text-sm">
        {{ $t('authentication.qrcodePrompt') }}
      </p>
    </div>

    <VbenButton class="mt-4 w-full" variant="outline" @click="goToLogin()">
      {{ $t('common.back') }}
    </VbenButton>
    <div class="mt-4 text-center text-sm">
      {{ $t('authentication.alreadyHaveAccount') }}
      <span
        class="text-primary hover:text-primary-hover cursor-pointer text-sm font-normal"
        @click="goToLogin()"
      >
        {{ $t('authentication.goToLogin') }}
      </span>
    </div>

    <!-- 保持模板部分不变 -->
  <div class="websocket-demo">
    <h2>WebSocket 示例</h2>
    
    <div class="status">
      连接状态: {{ isConnected ? '已连接' : '未连接' }}
      <button @click="toggleConnection">
        {{ isConnected ? '断开连接' : '建立连接' }}
      </button>
    </div>

    <div class="message-box">
      <input
        v-model="messageInput"
        type="text"
        placeholder="输入要发送的消息"
        @keyup.enter="sendMessage"
      />
      <button @click="sendMessage" :disabled="!isConnected">发送</button>
    </div>

    <div class="messages">
      <h3>接收到的消息:</h3>
      <ul>
        <li v-for="(message, index) in messages" :key="index">
          {{ message }}
        </li>
      </ul>
    </div>
  </div>
  </div>
</template>
<style scoped>
/* 样式保持不变 */
.websocket-demo {
  max-width: 600px;
  margin: 20px auto;
  padding: 20px;
  border: 1px solid #eee;
}

.status {
  margin: 20px 0;
  padding: 10px;
  background-color: #f5f5f5;
}

.message-box {
  margin: 20px 0;
}

.message-box input {
  padding: 8px;
  width: 200px;
  margin-right: 10px;
}

.messages {
  margin-top: 20px;
  text-align: left;
}

ul {
  list-style-type: none;
  padding: 0;
  max-height: 300px;
  overflow-y: auto;
}

li {
  padding: 5px;
  border-bottom: 1px solid #eee;
}
</style>
